package carlyang.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @author carlyang
 * 
 */
public class DBUtil {

	// 数据库地址
	private static final String dbUrl = "jdbc:mysql://localhost:3306/db_book?useUnicode=true&characterEncoding=utf-8&useSSL=false";
	// 用户名
	private static final String dbUserName = "carlyang";
	// 密码
	private static final String dbPassword = "yangdong";
	// 驱动名称
	private static final String jdbcName = "com.mysql.jdbc.Driver";

	public DBUtil() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 使用用户指定的数据库参数，获取数据库连接
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection(String dbUrl, String dbUserName,
			String dbPassword) throws Exception {
		Class.forName(jdbcName);// 可以不需要
		Connection con = DriverManager.getConnection(dbUrl, dbUserName,
				dbPassword);
		return con;
	}

	/*
	 * 使用默认的数据库，获取数据库连接
	 * 
	 * @return
	 * 
	 * @throws Exception
	 */
	public static Connection getConnection() throws Exception {
		Class.forName(jdbcName);// 可以不需要
		Connection con = DriverManager.getConnection(dbUrl, dbUserName,
				dbPassword);
		return con;
	}

	/**
	 * 关闭连接
	 * 
	 * @param con
	 * @throws Exception
	 */
	public static void close(Statement stmt, Connection con) throws Exception {
		if (stmt != null) {
			stmt.close();
			if (con != null) {
				con.close();
			}
		}

	}
	
	public static int createDatebase(Statement stmt,String database) throws Exception{
		String sqlCmd = "create database "+database;
		int result=stmt.executeUpdate(sqlCmd);
		System.out.println("操作的结果："+result+" 数据");
		return result;
	}
	
	public static int dropDatebase(Statement stmt,String database) throws Exception{
		String sqlCmd = "drop database "+database;
		int result=stmt.executeUpdate(sqlCmd);
		System.out.println("操作的结果："+result+" 数据");
		return result;
	}
	public static int showDatebase(Statement stmt) throws Exception{
		String sqlCmd = "show databases";
		int result=stmt.executeUpdate(sqlCmd);
		System.out.println("操作的结果："+result+" 数据");
//		while (result.next()) {
//			System.out.println("result"+result);
//			
//		}
		return result;
	}
	public static void useDatebase(Statement stmt,String database) throws Exception{
		String sqlCmd = "use "+database;
		int result=stmt.executeUpdate(sqlCmd);
		System.out.println("操作的结果："+result+" 数据");
	}
	
}
